package persistence

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"ruoyi/config"
	"time"
)

var MysqlDb *gorm.DB

/*
或使用mysql.Client()
*/

func MysqlInit() (*SystemRepositories, *MonitorRepositories, error) {
	//启用打印日志
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level: Silent、Error、Warn、Info
			Colorful:      false,       // 禁用彩色打印
		},
	)

	//换成自己的
	dsn := config.Database.UserName + ":" + config.Database.Password + "@tcp(" + config.Database.Host + ":" + config.Database.Port + ")/" + config.Database.DbName + "?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		fmt.Println("数据库连接失败")
		panic("数据库连接失败")
	}
	fmt.Println("数据库连接成功")
	MysqlDb = db
	sys, err := NewSystemRepositories(db)
	mon, err := NewMonitorRepositories(db)
	return sys, mon, err
}
